function ListNode (val) {
  this.val = val
  this.next = null
}

let Node1 = new ListNode(1)
let Node2 = new ListNode(2)
let Node3 = new ListNode(3)
let Node4 = new ListNode(4)
let Node5 = new ListNode(5)
Node1.next = Node2
Node2.next = Node3
Node3.next = Node4
Node4.next = Node5

/**
 * 循环实现
 * @param  head
 * @returns
 */
let reverseList = function (head) {
  if (!head) return null

  let pre = null,
    cur = head
  while (cur) {
    let tmp = cur.next
    cur.next = pre
    pre = cur
    cur = tmp
  }
  return pre
}

/**
 * 递归实现
 * @param head
 * @returns pre
 */
reverseList = head => {
  let reverse = (pre, cur) => {
    if (!cur) {
      return pre
    } else {
      let next = cur.next
      cur.next = pre
      reverse(cur, next)
    }
  }
  let a = reverse(null, head)
  //   console.log(a)
}

// let a = reverseList(Node1)
// console.log(a)

let reverseBetween = function (head, left, right) {
  if (head && head.next && left != right) {
    let h = (ln = new ListNode())
    ln.next = head
    for (let i = 0; i < left - 1; i++) {
      ln = ln.next
    }

    let tail = ln.next
    let front = ln
    let pre = tail
    let cur = pre.next

    for (let i = 0; i < right - left; i++) {
      let next = cur.next
      cur.next = pre
      pre = cur
      cur = next
    }

    front.next = pre
    tail.next = cur
    return h.next
  }
  return head
}

console.log(reverseBetween(Node1, 1, 4))
